package com.kehao.leetcode.jzoffer;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author Kehao.Chen
 * @version 1.0
 * @date 2022/6/29 14:29
 */
public class JZSolution040 {

    private int largestRectangleArea(int[] heights) {
        List<Integer> list = new ArrayList<>();
        list.add(0);
        for (int i = 0; i < heights.length; i++) {
            list.add(heights[i]);
        }
        list.add(0);
        Stack<Integer> stack = new Stack<>();
        stack.push(0);
        int result = 0;
        for (int i = 0; i < list.size();) {
            if(list.get(stack.peek())<=list.get(i)){
                stack.push(i);
                i++;
            }else {
                Integer pop = stack.pop();
                result = Math.max(result,(i-stack.peek()-1)*list.get(pop));
            }
        }
        return result;
    }

    public int maximalRectangle(String[] matrix) {
        if(matrix.length==0) return 0;
        int[][] intMatrix = new int[matrix.length][matrix[0].length()];
        int[] heights = new int[matrix[0].length()];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length(); j++) {
                intMatrix[i][j] = matrix[i].charAt(j)-'0';
            }
        }
        int result = 0;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length(); j++) {
                heights[j] = intMatrix[i][j] == 0?0:(heights[j]+1);
            }
            result = Math.max(result,largestRectangleArea(heights));
        }

        return result;
    }

    @Test
    public void test01(){
        String[] matrix = {"10100","10111","11111","10010"};
        int result = maximalRectangle(matrix);
        System.out.println(result);
    }

    @Test
    public void test02(){
        String[] matrix = {};
        int result = maximalRectangle(matrix);
        System.out.println(result);
    }

    @Test
    public void test03(){
        String[] matrix = {"1"};
        int result = maximalRectangle(matrix);
        System.out.println(result);
    }
}

